package myreference

import (
	"data/config"
	"public/message"
	"public/mylog"
	"public/mysqldb"
	"public/tools"
	"time"
)

type M_type string
type M_master int

const (
	TYPE_NORMAL M_type = "unique" // 唯一账号（用户名 身份证..） string
	TYPE_PK     M_type = "pk"     // 自增主键 int

	IS_MASTER M_master = 1  //对长
	NO_MASTER M_master = -1 //队员
	NO_CHANGE M_master = 0  //不变

	TYPE_TEAM   string = "team"
	TYPE_MEMBER string = "member"
)

//新增或修改团队基本信息
func OnSaveTeamBasic(info Team_info_tbl) (result TeamInfoRet) {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	result.Timestamp = time.Now().Unix()
	if len(info.Team_no) > 0 { //修改
		var tmp Team_info_tbl
		orm.Where("team_no = ?", info.Team_no).Find(&tmp)
		if len(info.Name) > 0 {
			tmp.Name = info.Name
		}
		if info.Is_vaild != 0 {
			tmp.Is_vaild = info.Is_vaild
		}
		info = tmp
	} else { //新增
		info.Team_no = tools.GetRandomString(5)
		info.Is_vaild = 1
		info.Create_time = time.Now()
	}
	err := orm.Save(&info).Error
	if err != nil {
		mylog.Error(err)
		result.Error_code = message.UnknownError
		result.Error_msg = message.MessageMap[message.UnknownError]
		return
	}
	result.Result = info
	return
}

//解散团队（删除团队及全部队员）
func OnRemoveTeam(team_no string) (result BaseRet) {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	result.Timestamp = time.Now().Unix()
	var tmp Team_info_tbl
	orm.Where("team_no = ? ", team_no).Find(&tmp)
	if tmp.Id == 0 {
		result.Error_code = message.NotFindError
		result.Error_msg = "team is not exist"
		return
	}
	orm.Delete(Team_info_tbl{}, "team_no = ?", team_no)
	return
}

//获取全部团队详情
//no空：全部
//type_: team / member
func OnGetTeamDetail(no, type_ string) (result TeamDetailRet) {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	result.Timestamp = time.Now().Unix()

	var teams []Team_info_tbl
	if len(no) > 0 {
		if type_ == TYPE_TEAM { //团队
			var tmp Team_info_tbl
			orm.Where("team_no = ? ", no).Find(&tmp)
			if tmp.Id == 0 {
				result.Error_code = message.NotFindError
				result.Error_msg = "team is not exist"
				return
			}
			orm.Where("team_no = ? ", no).Find(&teams)
		} else if type_ == TYPE_MEMBER { //队员
			var tmp []Team_member_tbl
			orm.Where("member = ? ", no).Find(&tmp)
			if len(tmp) > 0 {
				var tt []string
				for _, v := range tmp {
					tt = append(tt, v.Team_no)
				}
				orm.Where("team_no in (?)", tt).Find(&teams)
			} else {
				result.Error_code = message.NotFindError
				result.Error_msg = "member not in any team"
				return
			}

		} else {
			result.Error_code = message.ParameterInvalid
			result.Error_msg = "param type_ error"
			return
		}
	} else {
		orm.Find(&teams)
	}
	if len(teams) > 0 {
		for _, v := range teams {
			var one TeamDetailResult
			one.Team_no = v.Team_no
			one.Name = v.Name
			one.Is_vaild = v.Is_vaild
			one.Create_time = v.Create_time

			var m []Team_member_tbl
			orm.Where("team_no = ? ", v.Team_no).Find(&m)
			one.Member = m
			result.Result = append(result.Result, one)
		}
	}
	return
}

//新增团队并添加队员
func OnAddTeam(tname string, member []TeamMember) (result OneTeamDetailRet) {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	result.Timestamp = time.Now().Unix()
	var info TeamDetailResult
	team_no := tools.GetRandomString(5)
	info.Team_no = team_no
	info.Is_vaild = 1
	info.Create_time = time.Now()
	info.Name = tname

	err := orm.Table("team_info_tbl").Create(&info).Error
	if err != nil {
		mylog.Error(err)
		result.Error_code = message.UnknownError
		result.Error_msg = message.MessageMap[message.UnknownError]
		return
	}
	if len(member) > 0 {
		for _, v := range member {
			var tmp Team_member_tbl
			tmp.Member = v.Member
			tmp.Team_no = team_no
			tmp.Is_master = int(v.Is_master)
			tmp.Type = string(v.Type)
			tmp.Attach = v.Attach
			if orm.Create(&tmp).Error != nil {
				result.Error_code = message.RepeatSubmission
				result.Error_msg = "member is repeat"
				orm.Delete(Team_info_tbl{}, "team_no = ?", team_no) //回滚
				return
			}
			info.Member = append(info.Member, tmp)
		}
	}
	result.Result = info
	return
}

//新增队员
func OnAddMember(team_no string, member []TeamMember) (result OneTeamDetailRet) {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	result.Timestamp = time.Now().Unix()
	var info TeamDetailResult
	orm.Table("team_info_tbl").Where("team_no = ? ", team_no).Find(&info)
	if info.Id == 0 {
		result.Error_code = message.NotFindError
		result.Error_msg = "team is not exist"
		return
	}
	if len(member) > 0 {
		for _, v := range member {
			var tmp Team_member_tbl
			tmp.Member = v.Member
			tmp.Team_no = team_no
			tmp.Is_master = int(v.Is_master)
			tmp.Type = string(v.Type)
			tmp.Attach = v.Attach
			orm.Create(&tmp)
		}
	}
	orm.Where("team_no = ? ", team_no).Find(&info.Member)
	result.Result = info
	return
}

//删除队员
//last_delete:最后一名队员时是否删除团队 true：是 false:否
func OnDeleteMember(team_no, member string, last_delete bool) (result OneTeamDetailRet) {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	result.Timestamp = time.Now().Unix()
	var info TeamDetailResult
	orm.Table("team_info_tbl").Where("team_no = ? ", team_no).Find(&info)
	if info.Id == 0 {
		result.Error_code = message.NotFindError
		result.Error_msg = "team is not exist"
		return
	}
	var mt Team_member_tbl
	orm.Where("team_no = ? and member = ?", team_no, member).Find(&mt)
	if mt.Id == 0 {
		result.Error_code = message.NotFindError
		result.Error_msg = "member is not exist"
		return
	}
	orm.Delete(Team_member_tbl{}, "team_no = ? and member = ?", team_no, member)
	orm.Where("team_no = ? ", team_no).Find(&info.Member)
	if len(info.Member) == 0 && last_delete {
		//删除团队
		orm.Delete(Team_info_tbl{}, "team_no = ?", team_no)
		info = TeamDetailResult{}
	}
	result.Result = info
	return
}

//更新队员属性
//是否队长（1：是  0：否）
func OnUpdateMember(team_no, member, attach string, is_master M_master) (result OneTeamDetailRet) {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	result.Timestamp = time.Now().Unix()
	var info TeamDetailResult
	orm.Table("team_info_tbl").Where("team_no = ? ", team_no).Find(&info)
	if info.Id == 0 {
		result.Error_code = message.NotFindError
		result.Error_msg = "team is not exist"
		return
	}
	var mt Team_member_tbl
	orm.Where("team_no = ? and member = ?", team_no, member).Find(&mt)
	if mt.Id == 0 {
		result.Error_code = message.NotFindError
		result.Error_msg = "member is not exist"
		return
	}
	mp := make(map[string]interface{})
	mp["attach"] = attach
	if is_master != NO_CHANGE {
		mp["is_master"] = int(is_master)
	}
	orm.Table("team_member_tbl").Where("team_no = ? and member = ?", team_no, member).Updates(mp)

	orm.Where("team_no = ? ", team_no).Find(&info.Member)
	result.Result = info
	return
}
